export function filterTree(treeData, keyword, childrenName = "children", keywordName = "name") {
  if (!treeData) {
    return [];
  }
  if (!keyword) {
    return treeData;
  }
  const resList = [];
  for (let i = 0; i < treeData.length; i++) {
    const item = treeData[i];
    if (item[childrenName] && item[childrenName].length > 0) {
      const childrenNew = filterTree(item[childrenName], keyword, childrenName, keywordName);
      if (childrenNew.length > 0) {
        resList.push({
          ...item,
          [`${childrenName}`]: childrenNew
        });
      } else {
        if (item[keywordName].indexOf(keyword) > -1) {
          resList.push({
            ...item,
            [`${childrenName}`]: []
          });
        }
      }
    } else {
      if (item[keywordName].indexOf(keyword) > -1) {
        resList.push({
          ...item,
          [`${childrenName}`]: []
        });
      }
    }
  }
  return resList;
}

export function filterEmptyValue(obj) {
  const newObj = {};
  Object.keys(obj).map((key) => {
    if (obj[key]) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
}

export function getFileName(url, needExt = false) {
  const http = url.split("?")[0];
  const file = http.split("/");
  const name = file[file.length - 1];
  if (needExt) {
    return name;
  }
  const endArr = name.split(".");
  endArr.pop();
  return endArr.join(".");
}

export function fileListDecode(list) {
  if (list && list.length > 0) {
    const urls = list
      .map((item) => {
        const url = item.response ? (item.status === "done" ? item.response.data[0] : false) : item.url || false;
        return url;
      })
      .filter((li) => !!li);
    return urls.join(",");
  }
  return "";
}
export function fileListEncode(str) {
  if (str) {
    const urls = str.split(",");
    return urls.map((url, idx) => {
      const url_s = url.split("/");
      return {
        uid: `-${idx + 1}`,
        name: url_s[url_s.length - 1],
        status: 200,
        url
      };
    });
  }
  return [];
}

export function fillDelItemToList(item, listOld) {
  const idx = listOld.findIndex((li) => li.value === item.value);
  if (idx > -1) {
    return listOld;
  } else {
    return [item].concat(listOld);
  }
}

export function findAllParentIds(list) {
  if (!list) {
    return [];
  }
  let res = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.companyList && item.companyList.length > 0) {
      res.push(item.id);
    }
    res = [].concat(res, findAllParentIds(item.companyList));
  }
  return res;
}

export function buildGroupTreeMap(list) {
  if (!list) {
    return {};
  }
  let res = {};
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    res[item.id] = {
      label: item.name,
      value: item.id
    };
    if (item.childList && item.childList.length > 0) {
      res = {
        ...res,
        ...buildGroupTreeMap(item.childList)
      };
    }
  }
  return res;
}

export function formatGroupTree(list) {
  if (!list) {
    return [];
  }
  const res = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    const newItem = {
      title: item.name,
      value: item.id,
      key: item.id,
      disabled: !item.hasPermission
    };
    if (item.childList && item.childList.length > 0) {
      newItem["children"] = formatGroupTree(item.childList);
    }
    res.push(newItem);
  }
  return res;
}

export function formatCompanyTree(list, parent) {
  if (!list) {
    return [];
  }
  const res = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    const key = `${parent ? parent.id : "system"}_${item.type}_${item.id}`;
    res.push({
      title: item.name,
      key,
      value: key,
      children: formatCompanyTree(item.companyList, item)
    });
  }
  return res;
}

export function formatCompanyIdNameDict(list) {
  if (!list) {
    return [];
  }
  let dict = {};
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    dict[item.id] = item.name;
    if (item.companyList && item.companyList.length > 0) {
      dict = { ...dict, ...formatCompanyIdNameDict(item.companyList) };
    }
  }
  return dict;
}

export function findAreaArrFromMap(id, map) {
  try {
    const idInt = parseInt(id);
    let arr = [idInt];
    const item = map[idInt];
    if (item.parentId !== 0) {
      const arrP = findAreaArrFromMap(item.parentId, map);
      arr = [].concat(arrP, arr);
    }
    return arr;
  } catch (err) {
    return [];
  }
}

export function getExtFromUrl(str) {
  const strLst = str.split(".");
  const ext = strLst[strLst.length - 1];
  let format = "";
  if (["jpg", "jpeg", "png", "bmp", "gif"].includes(ext)) {
    format = "img";
  } else if (["doc", "docx", "xls", "xlsx", "ppt", "pptx"].includes(ext)) {
    format = "office";
  } else if (["pdf"].includes(ext)) {
    format = "pdf";
  } else if (["zip", "rar"].includes(ext)) {
    format = "zip";
  } else {
    format = "file";
  }
  return [format, ext];
}

const getDate = (date = new Date(), showTime = false) => {
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  month = month > 9 ? month : `0${month}`;
  day = day > 9 ? day : `0${day}`;
  if (!showTime) {
    return `${year}-${month}-${day}`;
  }
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();

  hour = hour > 9 ? hour : `0${hour}`;
  minute = minute > 9 ? minute : `0${minute}`;
  second = second > 9 ? second : `0${second}`;

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

function diffTime(time) {
  try {
    const minute = 1000 * 60;
    const hour = minute * 60;
    const day = hour * 24;
    const halfAMonth = day * 15;
    const month = day * 30;

    const diffValue = new Date().getTime() - new Date(time).getTime();

    const monthC = diffValue / month;
    const weekC = diffValue / (7 * day);
    const dayC = diffValue / day;
    const hourC = diffValue / hour;
    const minC = diffValue / minute;
    let result = "";
    if (parseInt(monthC) >= 1) {
      result = parseInt(monthC) + "个月前";
    } else if (parseInt(dayC) > 1) {
      result = parseInt(dayC) + "天前";
    } else if (parseInt(dayC) === 1) {
      result = "昨天";
    } else if (parseInt(hourC) >= 1) {
      result = parseInt(hourC) + "小时前";
    } else if (parseInt(minC) >= 1) {
      result = parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    return result;
  } catch (err) {
    return "--";
  }
}

export { getDate, diffTime };
